package com.retch.wenchengmao.recodeauthutils.bean;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;

/**
 * author:wenchengmao
 * time:  2017/3/27.
 * email: wenchengmao@yeah.net
 */
//获取权限的封装类
public class AuthUtil {
    //获取单个权限
    public static void getPermission(Activity activity,String permission,int requestCode) {
        int permissions = ContextCompat.checkSelfPermission(activity, permission);
        if (permissions != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode);
        }
        else
            return;
    }

    //获取多个权限
    public static void getMultiPermission(Activity activity,String [] permissions,int requestCode)
    {
        int permission []=new int[100];
        List<String> list=new ArrayList<>();
        for(int i=0;i<permissions.length;i++)
        {
            permission[i]=ContextCompat.checkSelfPermission(activity,permissions[i]);
            if(permission[i]!=PackageManager.PERMISSION_GRANTED)
            {
                list.add(permissions[i]);
            }
        }

    }

    public static void getPermissions(Activity activity,String []permission)
    {
        List<String> needRequestPermissonList= findDeniedPermissions(activity,permission);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            //list.toarray将集合转化为数组
            ActivityCompat.requestPermissions(activity,
                    needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]),
                    2);
        }
    }

    //获取需要授权的权限
    public static List<String> findDeniedPermissions(Activity activity,String [] permission)
    {

        List<String> needRequestPermissonList = new ArrayList<String>();
        //for (循环变量类型 循环变量名称 : 要被遍历的对象)
        for (String perm : permission) {
            if (ContextCompat.checkSelfPermission(activity,
                    perm) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    activity, perm)) {
                needRequestPermissonList.add(perm);
            }
        }
        return needRequestPermissonList;
    }


}
